package ar.edu.itba.pod.Legajo47342.communication;

import java.net.ConnectException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import ar.edu.itba.pod.Legajo47342.Node;
import ar.edu.itba.pod.simul.communication.ClusterCommunication;
import ar.edu.itba.pod.simul.communication.Message;
import ar.edu.itba.pod.simul.communication.MessageListener;

public class ClusterCommunicationImpl implements ClusterCommunication {

	private Node node;
	private MessageListener listener;
	
	public ClusterCommunicationImpl(Node node) throws RemoteException {
		super();
		this.node = node;
		this.listener = new MessageListenerImpl(node);
		
		UnicastRemoteObject.exportObject(this, 0);
	}
	
	@Override
	public void broadcast(Message message) throws RemoteException {
		
		for (String n : node.getRandomNodes(null)) {
			System.out.println("sent to "+n);
			try {
				if(!send(message, n)){
					return;
				}
			} catch (RemoteException e) {
				if (e.getCause().getClass().equals(ConnectException.class)) {
					//el nodo esta caido, lo saco de mis nodos
					node.getClusterNodes().remove(n);
					node.getLoads().remove(n);
					System.out.println(n+" seems down. Continue with the rest...");
				}else {
					throw e;
				}
			}
		}

	}

	@Override
	public boolean send(Message message, String nodeId) throws RemoteException {
		return node.getManager().getConnectionManager(nodeId).
					getGroupCommunication().getListener().
					onMessageArrive(message);
	}

	@Override
	public MessageListener getListener() throws RemoteException {
		return listener;
	}

}
